package com.shanhesoft.java.common.config;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shanhesoft.java.common.core.constant.CommonConstants;
import com.shanhesoft.java.common.core.util.Result;
import com.shanhesoft.java.common.core.util.StringUtil;
import com.shanhesoft.java.modules.exam.domain.VirtualTrainingDetailInstance;
import com.shanhesoft.java.modules.exam.service.VirtualTrainingDetailInstanceService;
import com.shanhesoft.java.modules.exam.service.impl.RancherService;

@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
@PropertySource(value = {"file:./config/config.properties"}, encoding="utf-8")    // 3.配置文件位置
public class DeleteContainerScheduleTask {
	
	@Autowired
	private RancherService rancherService;
	@Autowired
	private VirtualTrainingDetailInstanceService virtualTrainingDetailInstanceService;

	@Async
    @Scheduled(cron = "${rancher.container.delete.cron}")
	public void deleteContainers() {
		QueryWrapper<VirtualTrainingDetailInstance> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne("container_state", "removed");
		queryWrapper.ne("container_state", "purged");
		List<VirtualTrainingDetailInstance> list = virtualTrainingDetailInstanceService.list(queryWrapper);
		for (VirtualTrainingDetailInstance virtualTrainingDetailInstance : list) {
			String containerId = virtualTrainingDetailInstance.getContainerId();
			if(StringUtil.isEmpty(containerId)) {
				continue;
			}
			Result deleteContainer = rancherService.deleteContainer(containerId);
			if(CommonConstants.FAIL.intValue() == deleteContainer.getCode()) {
				continue;
			}
			virtualTrainingDetailInstance.setContainerState("removed");
			virtualTrainingDetailInstanceService.saveOrUpdate(virtualTrainingDetailInstance);
		}
	}

}
